package com.cipe.cmrs.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cipe.cmrs.model.ref.Link;
import com.cipe.cmrs.model.ref.LinkCategory;
import com.cipe.cmrs.service.LinkCategoryService;
import com.cipe.cmrs.service.ref.BaseRefService;
import com.cipe.cmrs.util.UserUtil;

@Service
public class LinkCategoryServiceImpl extends BaseRefService implements LinkCategoryService {
    @Transactional(propagation = Propagation.NEVER) // TODO: I don't know why JPA doesn't acknowledge this.
    @SuppressWarnings("unchecked")
    public List<LinkCategory> getAllAllowedLinks() {
        List<LinkCategory> results = new ArrayList<LinkCategory>();
        Set<Link> userAllowedLinks = UserUtil.INSTANCE.getCurrentUserAllowedLinks();
        List<LinkCategory> categories = (List<LinkCategory>) findAllByType(LinkCategory.class);
        if (categories != null && categories.size() > 0) {
            for (int i = categories.size() - 1; i >= 0; i--) {
                LinkCategory category = categories.get(i);
                List<Link> allowedLinks = new ArrayList<Link>();

                for (Link link : category.getLinks()) {
                    if (userAllowedLinks.contains(link)) {
                        Link bean = new Link();
                        BeanUtils.copyProperties(link, bean);
                        allowedLinks.add(bean);
                    }
                }

                if (allowedLinks.size() > 0) {
                    LinkCategory bean = new LinkCategory();
                    BeanUtils.copyProperties(category, bean);
                    bean.setLinks(allowedLinks);
                    results.add(bean);
                }
            }
        }
        
        Collections.sort(results, new Comparator<LinkCategory>() {
            public int compare(LinkCategory o1, LinkCategory o2) {
                return o1.getDisplayOrder().compareTo(o2.getDisplayOrder());
            }
        });
        return results;
    }
}
